package cn.hw.server.service;

import cn.hw.server.cacheAop.MyCacheEvict;
import cn.hw.server.cacheAop.MyCacheable;
import cn.hw.server.entity.User;
import cn.hw.server.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Optional;

@Service
public class UserService {


    @Autowired
    private UserRepository userRepository;

    public User findByLoginName(String loginName) {
        return userRepository.findByLoginName(loginName);
    }

    @MyCacheEvict(allEntries = true)
    public void add(String nickName, String loginName, String loginPassword, String address, String tel, String sex) {
        User user = new User();
        user.setNickName(nickName);
        user.setLoginName(loginName);
        user.setAddress(address);
        user.setSex(sex);
        user.setTel(tel);
        user.setLoginPassword(DigestUtils.md5DigestAsHex((loginName + loginPassword).getBytes()));
        userRepository.save(user);
    }

    @MyCacheable
    public Page<User> list(Integer page, Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        return userRepository.findAll(pageable);
    }

    @MyCacheEvict(allEntries = true)
    public boolean update(Integer id, String nickName, String address, String tel, String sex) {
        Optional<User> byId = userRepository.findById(id);
        if (byId.isPresent()) {
            User user = byId.get();
            user.setNickName(nickName);
            user.setAddress(address);
            user.setTel(tel);
            user.setSex(sex);
            return true;
        }
        return false;
    }

    @MyCacheEvict(allEntries = true)
    public void delete(Integer id) {
        userRepository.deleteById(id);
    }

    @MyCacheEvict(allEntries = true)
    public boolean resetPwd(Integer id) {
        Optional<User> byId = userRepository.findById(id);
        if (byId.isPresent()) {
            User user = byId.get();
            user.setLoginPassword(DigestUtils.md5DigestAsHex((user.getLoginName() + "123456").getBytes()));
            return true;
        }
        return false;
    }

    @MyCacheable
    public User findById(Integer id) {
        return userRepository.findById(id).get();
    }


}
